package com.smart.thirteen.autokey;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 返回key
 *
 * @author junrui.wang
 * @create 2019/10/21
 */
public class AutoGenerateKey {
    public static void main(String[] args) throws SQLException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:com/smart/thirteen/applicationContext-template.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");

        Connection connection = jdbcTemplate.getDataSource().getConnection();
        Statement statement = connection.createStatement();
        String sql = "INSERT INTO t_topic(topic_title,user_id) VALUES ('test', '1111')";
        statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()){
            int key = rs.getInt(1);
            System.out.println(key);
        }

    }
}
